﻿<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" Inherits="Pages_Operators_RouteItem" Codebehind="RouteItem.aspx.cs" %>

<%@ Register Src="../Operators/Ascx/ProgramPopup.ascx" TagName="ProgramPopup" TagPrefix="uc1" %>
<%@ Register Src="~/Tools/NumericBox.ascx" TagName="NumericBox" TagPrefix="num" %>
<asp:Content ID="Content1" ContentPlaceHolderID="title" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="using" runat="Server">
    <script type="text/javascript" src="/js/jquery.metadata.js"></script>
    <script type="text/javascript" src="/js/autoNumeric-1.7.4.js"></script>
    <script type="text/javascript" src="/Pages/Operators/Js/route.js"></script>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="header" runat="Server">
    <uc1:ProgramPopup ID="ProgramPopup" runat="server" />
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="content" runat="Server">
    <table cellspacing="10" class="popup">
        <tr>
            <td rowspan="8">
                <div class="tabs" style="min-height: 300px">
                    <ul class="tabNavigation">
                        <li><a href="#routeinfo"><span>Route Info</span></a></li>
                        <li><a href="#program"><span>Default Activities</span></a></li>
                    </ul>
                    <!-- tab containers -->
                    <div id="routeinfo">
                        <table>
                            <tr>
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            Route #:</div>
                                        <div class="field">
                                            <asp:HiddenField ID="hidRouteID" runat="server"></asp:HiddenField>
                                            <asp:DropDownList ID="ddlRouteNumberInput" runat="server">
                                            </asp:DropDownList>
                                            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*"
                                                ControlToValidate="ddlRouteNumberInput"></asp:RequiredFieldValidator>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            Sub Route:</div>
                                        <div class="field">
                                            <asp:TextBox ID="txtSubRoute" MaxLength="1" Style="text-transform: uppercase" runat="server">
                                            </asp:TextBox>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            Route Name:</div>
                                        <div class="field">
                                            <asp:TextBox ID="txtRouteNameInput" runat="server" Width="368px"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="*"
                                                ControlToValidate="txtRouteNameInput"></asp:RequiredFieldValidator>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            Description:</div>
                                        <div class="field">
                                            <asp:TextBox ID="txtDescriptionInput" runat="server" Rows="5" TextMode="MultiLine"
                                                Width="368px"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="*"
                                                ControlToValidate="txtDescriptionInput"></asp:RequiredFieldValidator>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            Num of meals:</div>
                                        <div>
                                            <asp:CheckBoxList ID="cblNumOfMeals" runat="server" RepeatColumns="3" RepeatDirection="Horizontal">
                                                <asp:ListItem Value="1" alt="1" Text="Breakfast" />
                                                <asp:ListItem Value="2" alt="2" Text="Lunch" />
                                                <asp:ListItem Value="4" alt="4" Text="Dinner&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b style='color: red'>Day 1</b>" />
                                                <asp:ListItem Value="8" alt="8" Text="Breakfast" />
                                                <asp:ListItem Value="16" alt="16" Text="Lunch" />
                                                <asp:ListItem Value="32" alt="32" Text="Dinner&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b style='color: red'>Day 2</b>" />
                                                <asp:ListItem Value="64" alt="64" Text="Breakfast" />
                                                <asp:ListItem Value="128" alt="128" Text="Lunch" />
                                                <asp:ListItem Value="256" alt="256" Text="Dinner&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b style='color: red'>Day 3</b>" />
                                            </asp:CheckBoxList>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            Base on Shuttle:</div>
                                        <div>
                                            <asp:CheckBox ID="chkHasShuttle" runat="server" />
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            Base on Flight:</div>
                                        <div>
                                            <asp:CheckBox ID="chkHasFlight" runat="server" />
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            Meal providers:</div>
                                        <div>
                                            <asp:TextBox ID="txtProviderName" runat="server" Width="368px"></asp:TextBox>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div id="program">
                        <div id="divProgram">
                        </div>
                    </div>
                </div>
                <div class="item">
                    <span id="spanNotice">
                        <asp:Literal ID="litNotice" runat="server" />
                    </span>
                </div>
                <div id="button">
                    <a id="btnSave" href="javascript:void(0)">Save</a> <a id="btnClose" href="/Pages/Operators/RouteList.aspx">
                        Close</a>
                </div>
            </td>
        </tr>
    </table>
    <script type="text/javascript">
        // Global Variables
        var pageSize = 20;

        // Clear Provider
        function clear() {
            $("#<%=hidRouteID.ClientID %>").val('');
            $("#<%=ddlRouteNumberInput.ClientID %>").val(-1);
            $("#<%=txtSubRoute.ClientID %>").val('');
            $("#<%=txtRouteNameInput.ClientID %>").val('');
            $("#<%=txtDescriptionInput.ClientID %>").val('');
            $("#<%=txtProviderName.ClientID %>").val('');

            $("#<%=chkHasShuttle.ClientID %>").removeAttr('checked');
            $("#<%=chkHasFlight.ClientID %>").removeAttr('checked');

            $('#<%=cblNumOfMeals.ClientID %> input[type="checkbox"]:checked').each(function () {
                $(this).removeAttr('checked');
            });

            $("#<%=txtRouteNameInput.ClientID %>").focus();
        }

        function loadProgram(programs, pageNumber) {
            $('#divProgram').setTemplateURL("/Pages/Operators/template/defaultProgramTemplate.htm");
            $('#divProgram').processTemplate({ List: programs, IsAdmin: '<%=HttpContext.Current.User.IsInRole(define.AdminRole) %>' });

            $("#gridProgram a.btnNew").button().click(function () {
                clearProgramForm();

                $("#program-dialog").dialog("open");
            });

            initializeEvents();
        }

        function insert(route) {
            alert('Inserting');
            var result = false;
            defaultParameters = "{ route:" + JSON.stringify(route) + "}";
            alert('Serialize');
            $.ajax({
                type: "POST",
                url: "/Update.asmx/InsertRoute",
                data: defaultParameters,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: false,
                success: (function Success(data, status) {
                    alert('Done');
                    if (data.d) {
                        $("#litNotice").text("INSERT SUCCESSFUL.");
                        $("#litNotice").show(1);
                        $("#litNotice").hide(39);
                        result = true;
                    }
                    else
                        $("#litNotice").text("INSERT FAILS.");
                }),
                error: (function Error(XMLHttpRequest, status, error) {
                    var err = eval("(" + XMLHttpRequest.responseText + ")");
                    alert('Insert route failed. Detail: ' + err.Message);
                })
            });
            return result;
        }

        function update(route) {
            var result = false;
            defaultParameters = "{ route:" + JSON.stringify(route) + "}";
            $.ajax({
                type: "POST",
                url: "/Update.asmx/UpdateRoute",
                data: defaultParameters,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: false,
                success: (function Success(data, status) {
                    if (data.d) {
                        $("#litNotice").text("UPDATE SUCCESSFUL.");
                        result = true;
                    }
                    else
                        $("#litNotice").text("UPDATE FAILS.");
                }),
                error: (function Error(XMLHttpRequest, status, error) {
                    var err = eval("(" + XMLHttpRequest.responseText + ")");
                    alert('Update route failed. Detail: ' + err.Message);
                })
            });
            return result;
        }

        function getRoute() {
            var route = {};

            if ($.trim($("#<%=hidRouteID.ClientID %>").val()) != "")
                route.RouteID = $("#<%=hidRouteID.ClientID %>").val();
            route.RouteNumber = parseInt($("#<%=ddlRouteNumberInput.ClientID %>").val());
            route.SubRouteCode = $("#<%=txtSubRoute.ClientID %>").val();
            route.RouteName = $("#<%=txtRouteNameInput.ClientID %>").val();
            route.Description = $("#<%=txtDescriptionInput.ClientID %>").val();

            route.NumOfMeals = 0;
            $('#<%=cblNumOfMeals.ClientID %> input[type="checkbox"]:checked').each(function () {
                var i = parseInt($(this).parent().attr("alt"));
                route.NumOfMeals = route.NumOfMeals | i;
            });

            route.HasShuttle = $("#<%=chkHasShuttle.ClientID %>").is(":checked");
            route.HasFlight = $("#<%=chkHasFlight.ClientID %>").is(":checked");
            route.ProviderName = $("#<%=txtProviderName.ClientID %>").val();

            getProgram(route);

            return route;
        }

        $(document).ready(function () {

            var routeID = '<%=RouteID %>';

            if (routeID != '') {
                // load provider
                $.ajax({
                    type: "POST",
                    url: "/Get.asmx/GetRoute",
                    data: "{ routeID:'" + routeID + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: false,
                    success: (function Success(data, status) {
                        var route = data.d;
                        $("#<%=ddlRouteNumberInput.ClientID %>").attr('disabled', true);
                        $("#<%=hidRouteID.ClientID %>").val(route.RouteID);
                        $("#<%=ddlRouteNumberInput.ClientID %>").val(route.RouteNumber);
                        $("#<%=txtSubRoute.ClientID %>").val(route.SubRouteCode);
                        $("#<%=txtRouteNameInput.ClientID %>").val(route.RouteName);
                        $("#<%=txtDescriptionInput.ClientID %>").val(route.Description);
                        $("#<%=txtProviderName.ClientID %>").val(route.ProviderName);

                        if (route.NumOfMeals != null) {
                            $('#<%=cblNumOfMeals.ClientID %> input[type="checkbox"]').each(function () {
                                var i = parseInt($(this).parent().attr("alt"));
                                $(this).attr('checked', (route.NumOfMeals & i) == i);
                            });
                        }

                        $("#<%=chkHasShuttle.ClientID %>").attr('checked', route.HasShuttle);
                        $("#<%=chkHasFlight.ClientID %>").attr('checked', route.HasFlight);
                        loadProgram(route.RouteServiceCollection, 1);
                    }),
                    error: (function Error(XMLHttpRequest, status, error) {
                        var err = eval("(" + XMLHttpRequest.responseText + ")");
                        $("#program").html(err.Message).fadeIn(1000);
                    })
                });
            }
            else {
                $("#<%=ddlRouteNumberInput.ClientID %>").removeAttr('disabled');
                clear();

                loadProgram([], 1);
            }

            var validControl = $([]).add($("#<%=ddlRouteNumberInput.ClientID %>"))
                                .add($("#<%=txtSubRoute.ClientID %>"));

            function validation() {
                var isValid = true;
                var first = true;
                validControl.each(function () {
                    isValid &= $(this).valid();
                    if (!isValid && first) {
                        $(this).focus();
                        first = false;
                    }
                });

                if ($("#<%=hidRouteID.ClientID %>").val() == "" && checkRoute($("#<%=ddlRouteNumberInput.ClientID %>").val(), $("#<%=txtSubRoute.ClientID %>").val())) {
                    $("#litNotice").text("This Route Number & Sub Route is exists.");
                    return false;
                }

                if (!isValid) return false;

                return true;
            }

            $("#btnSave").button().click(function () {
                if (!validation()) return;

                var route = getRoute();
                if ($("#<%=hidRouteID.ClientID %>").val() == "") {
                    alert('before insert');
                    if (insert(route)) {
                        clear();
                        window.location.href = "/Pages/Operators/RouteList.aspx";
                    }
                }
                else {
                    if (update(route)) window.location.href = "/Pages/Operators/RouteList.aspx";
                }
            });
            $("#btnClose").button();

        });

    </script>
</asp:Content>
